import os
from math import ceil
from django.shortcuts import render
from django.db.models import Max
from django.shortcuts import render,redirect
from django.http import HttpResponseRedirect
from pyexcel_io import save_data

from .models import Student, Class    #  from .models import *   # from . import models

# Create your views here.
def index(request):
    """ 获取学生列表"""
    # 计算分页索引
    page_no = int(request.GET.get('page_no', 1))
    page_size = int(request.GET.get('page_size', 3))
    start_index = (page_no - 1) * page_size
    end_index = page_no * page_size

    # todo 多条件过滤
    # name_like = "明"  gender="女"




    # 查询
    rows_amount = Student.objects.all().count()
    # page_amount = (rows_amount-0.1) // page_size + 1      #9条/每页3条 整除是导致总页数多算了1.
    page_amount = ceil(rows_amount / page_size)
    page_amount_list = [i for i in range(page_amount)]       # [0,1,2]
    if page_size > page_amount or page_size < 0:
        error_message = '请求页码数超过最大页码'
    student_list = Student.objects.all().order_by('no')[start_index: end_index]

    context = {
        'student_list': student_list,
        'page_amount_list': page_amount_list,
        'page_no': page_no,
        'page_previous': page_no - 1,
        'page_next': page_no+1,
    }
    return render(request, 'index.html', context)

def api_index(request):
    """
    :return
    '
    {
     "code":200,
     "message":"ok",
     "count":"80",
     "student_list":[
            {"id":1, "no":"001", "name":"张三", "add_time":"2019-10-09"}
            ]
    }
    """

def index2(request):
    pass
    # 用django自带的paginator来实现


def add(request):
    """ 添加表单 """
    # print(request.method)   # GET
    # 有些教程把get和post写到一个视图函数中，通过if request.method == 'GET':
    # 走不同逻辑。但post请求出错时会弹出“表单已提交是否重新加载可能丢失资料的”烦人提示，不利于调试。
    # 所以还是推荐分两个请求来做，一个返回添加页面，一个做存储用户提交数据

    # 获取生成下一个学号
    max_no = Student.objects.aggregate(Max('no'))   # {'no__max': 7}
    next_no = max_no['no__max'] + 1
    # SELECT  max(id) as max_id  from student_student;
    context = {
        'next_no': next_no,
    }
    return render(request, 'add.html', context)

def do_add(request):
    """ POST 存储用户提交的新学生信息 """
    assert request.method == 'POST', 'error: 表单http请求方式应为post'
    # 取参数
    # dj框架自带了 表单类，先跟model映射好，自动生成表单，自带方法form.isvalid合法性验证  form.save()保存。
    # 但这种方式隐藏了原理，前端不容易改css，需要记忆额外的属性来自定义表单，在具备前端基础的情况下不推荐使用dj自带的。
    # 我们这里为了理解原理，前端手写html表单，后端存
    args = request.POST
    file = request.FILES        # 文件会存到这个字段里，内存中，open方法打开
    stu_no = args['no']
    stu_name = args['name']
    stu_age = args['age']
    stu_gender = args['gender']
    stu_phone = args['phone']
    # 验证
    # 存储
    student = Student()
    student.no = stu_no
    student.name = stu_name
    student.age = stu_age
    if stu_gender == '男':
        student.gender = 1
    elif stu_gender == '女':
        student.gender = 2
    student.phone = stu_phone
    student.save()
    return render(request, 'success.html')



def export_excel(request):
    """导出所有学生信息到excel文件"""
    # 数据库查询学生数据
    # 数据拼成二维数组  （第一行为字段名，后面的数据行，（选做）合并前两行、填充背景色和修改字体字号）
    # save(data,afile='media/download//student_info.xlsx')
    # redirect(to='域名/'media/download//student_info.xlsx')
    students = Student.objects.all()
    s1 = [
        ['id', 'no', 'name', 'age', 'gender', 'phone'],
    ]
    for stu in students:
        s1.append([stu.id, stu.no, stu.name, stu.age, stu.gender, stu.phone])
        save_data(data=s1, afile=r'C:\Users\吕纬康\PycharmProjects\django_student\media\download\test.xlsx')
    return HttpResponseRedirect('/media/download/test.xlsx')



def update(request,stu_no):
    student = Student.objects.get(no=stu_no)
    context = {
        'stu':student   # stu现在是student 你在网页里面stu.no  就是调用了库里的学号
    }
    return render(request,'update.html',context)

def do_update(request,stu_no):
    assert request.method == 'POST','error:表单http请求方式应为post'
    a = request.POST
    file= request.FILES
    no = a['no']
    name = a['name']
    age = a['age']
    gender = a['gender']
    phone = a['phone']
    new_img = file['avatar']
    new_student = Student.objects.get(no=stu_no)
    print(new_student)
    new_student.no = no
    new_student.name = name
    new_student.age = age
    new_student.gender = gender
    new_student.phone = phone
    new_student.avatar = new_img
    new_student.save()
    return redirect(to='/student/index/')

def delete(request):
    """删除学生信息"""
     #获取所有信息
    student_id = Student.objects.get(id=int(request.GET.get("stu_id")))
    stu_id1 =int(request.GET.get("stu_id"))
    context ={"student_id":student_id,
                'stu_id1':stu_id1}

    return render(request, 'delete.html',context)
def do_delete(request):
    student_id = Student.objects.get(id=int(request.GET.get("stu_id1"))).delete()
    return HttpResponseRedirect('/student/index/')


def cloth_sale_line(request):
    # 后端渲染。缺点不适合做动态图
    # 获取数据。请求其他接口读数据库
    # 拼前端表格所需的变量
    legend='销量'
    xAxis = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    context = {}
    return render('student/8echart.html',context)

# def cloth_sale_line_api(request):
#     # 前后端分离，前端渲染图表，后端复杂返回数据
#     legend = '销量'
#     xAxis = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
#     context = {}
#     return json.dumps(centext)
 



    # 分页功能原理：
# select * from student_student limit 0, 3;  -- 学生1到3（包含3）
# select * from student_student limit 1, 3;  -- 学生2到4
# -- limit跟python中的列表切片很像但参数含义不一样。limit 1, 3 下标（从0开始计第一行）1， 3表示向后取的行数。
# select * from student_student limit 6, 3;
# select count(id) as page_amount  from student_student; -- 计算总行数
#
# page_no 第几页   page_size 一页显示几条   page_amount 总数据个数
#         1            10
# select * from student_student limit 0, {page_size};
# 第1页  每页10条                     0      10
# 第2页                               10     10
#                                     20     10
#                            start_index = (page_no-1)*page_size
# 总页数    总行除以每页数向上取整  page_amount//page_size+1
#
# student_list = Student.objects.all().order_by('no')[1: 3]
#     start_index = (page_no - 1) * page_size
#     end_index = page_no * page_size